package com.jnu.assistant.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.jnu.assistant.pojo.Result;
import com.jnu.assistant.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        log.info("请求的url：{}",url);
        if(url.contains("login")){
            log.info("登录操作，放行....");
            return true;
        }

        String jwt=request.getHeader("token");
        if(!StringUtils.hasLength(jwt)){
            log.info("令牌为空，用户未登录");
            Result error=Result.error("NOT_LOGIN");
            String noLogin= JSONObject.toJSONString(error);
            response.getWriter().write(noLogin);
            return  false;
        }

        try {
            JwtUtils.parseJWT(jwt); // 解析JWT获取Claims
        }catch (Exception e){
            e.printStackTrace();
            log.info("令牌解析失败，返回未登录错误信息");
            Result error=Result.error("NOT_LOGIN");
            String noLogin= JSONObject.toJSONString(error);
            response.getWriter().write(noLogin);
            return false;
        }


        log.info("令牌合法，通过");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
